<?php 
/**
 * 角色管理
 * @author Administrator
 *
 */
class roleManage extends CControllerManageBase{
	public function show(){
		$model = new roleModel();
		$pageIndex = $this->getRequestData("page","GET",1);
		$pageSize = 10;
		$c = 0;
		$list = $model->selectPage($pageIndex,$pageSize,"role_id,role_name,description,create_time","del_flag=0","role_id","",$c);

		$pageStr = CPage::showPage($pageIndex,$pageSize,$c);
		$this->setMenu("角色列表");
		$this->render("role/list",array("list"=>$list,"pageStr"=>$pageStr));
	}

	public function add(){
		$errorStr="";
		$rule=array(
			"txt_role_name"=>array(
				"formValidator"=>array("tipid"=>"txt_role_name_tip","empty"=>"false","onshow"=>"请输入角色名称","onfocus"=>"请输入角色名称","oncorrect"=>"输入正确"),
				"inputValidator"=>array("min"=>"1","onerror"=>"角色名称不能为空")
			),
		);
		$this->formValidator->init(array("formID"=>"tbl_base_roleForm"));
		$this->formValidator->setRules($rule);
		if($_POST){
			$modelInfo = array();
			$modelInfo["role_name"] = $this->getRequestData("txt_role_name");//角色名称
			$modelInfo["del_flag"] = $this->getRequestData("txt_del_flag");//删除标记
			$modelInfo["description"] = $this->getRequestData("txt_description");//描述
			$modelInfo["create_time"] = $this->getRequestData("txt_create_time");//创建时间
			$modelInfo["update_time"] = $this->getRequestData("txt_update_time");//
			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
	            //角色类
	            $roleObj = new roleModel();
	            //角色模块类
	            $roleModuleObj = new roleModuleModel();
	
	            //模块类
	            $moudObj = new moduleModel();
	            //模块列表
	            $mData = $moudObj->selectAll();
	
	            $roleName = $this->getRequestData('txt_role_name');
	            $roleDesc = $this->getRequestData('txt_description');
	            
	            //添加角色
	            $roleId = $roleObj->insert(array("role_name" => $roleName, "del_flag" => 0, "description" => $roleDesc, "create_time" => date('Y-m-d H:i:s'), "update_time" => date('Y-m-d H:i:s')));
	
	            //添加权限
	            foreach ($mData as $key => $value)
	            {
	                $moudleId = $this->getRequestData($value['module_id']);
	                if ($moudleId)
	                {
	                    $rightValue = array_sum($moudleId);
	                    $roleModuleObj->insert(array("role_id" => $roleId, "module_id" => $value['module_id'], "right_value" => $rightValue));
	                }
	            }
	            if($roleId>0)
	            {
	            	$this->sysMsg("新增成功",0,array(array("text"=>"返回角色列表","href"=>$this->_manageDomain."roleManage/show/"),array("text"=>"继续新增","href"=>$this->_manageDomain."roleManage/add/")));
	            }
				else
				{
					$this->sysMsg("新增失败",1);
				}
			}
		}
		
		//显示添加页面
        $mRightObj = new moduleRightModel();
        $mData = $mRightObj->selectAllModuleRightInfo();

		//模块组
		$moduleGroups = array();
		//取所有的模块组
		$lastGroup = '';
		foreach ($mData as $key => $value)
		{
			if ($lastGroup != $value['module_group_id'])
			{
				$moduleGroups[] = array('module_group_id' => $value['module_group_id'], 'group_name' => $value['group_name'], 'group_sort' => $value['group_sort'], 'modules' => null);
				$lastGroup = $value['module_group_id'];
			}
		}
		
		//取Group的Module
		foreach ($moduleGroups as & $groupValue)
		{
			$groupId = intval($value['module_group_id']);
			$lastModuleID = 0;
			foreach ($mData as & $value)
			{
                    //echo $lastModuleID,'-',$value['module_id'],'<br />';
				if ($value['module_group_id'] == $groupValue['module_group_id'] && intval($value['module_id']) != $lastModuleID)
				{
 					$arrayRights = array();
					$lastModuleID = intval($value['module_id']);
					//取Module的rights
					foreach ($mData as $moduleValue)
					{
						if ($value['module_id'] == $moduleValue['module_id'])
						{
							$arrayRights[] = array('module_right_id' => $moduleValue['module_right_id'], 'right_value' => $moduleValue['right_value'], 'right_name' => $moduleValue['right_name'], 'right_ename' => $moduleValue['right_ename']);
						}
					}
					$groupValue["modules"][] = array('module_id' => $value['module_id'], 'module_name' => $value['module_name'], 'module_sort' => $value['sort_num'], 'rights' => $arrayRights);
				}
			}
		}
		
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"角色列表","href"=>$this->_manageDomain."roleManage/show/"),array("text"=>"角色新增")));
		$this->render("role/add",array("error"=>$errorStr,"rightData"=>$moduleGroups));
	}

	public function edit(){
		$role_id = $this->getRequestData("id","GET");
		$modelInfo = array();
		$errorStr = "";

		$rule=array(
			"txt_role_name"=>array(
				"formValidator"=>array("tipid"=>"txt_role_name_tip","empty"=>"false","onshow"=>"请输入角色名称","onfocus"=>"请输入角色名称","oncorrect"=>"输入正确"),
				"inputValidator"=>array("min"=>"1","onerror"=>"角色名称不能为空")
			)
		);
		$this->formValidator->init(array("formID"=>"tbl_base_roleForm"));
		$this->formValidator->setRules($rule);

		$model=new roleModel();
		if($_POST){
			$modelInfo["role_id"] = $role_id;
			$modelInfo["role_name"] = $this->getRequestData("txt_role_name");//角色名称
			$modelInfo["del_flag"] = 0;//删除标记
			$modelInfo["description"] = $this->getRequestData("txt_description");//描述
			$modelInfo["update_time"] = date('Y-m-d H:i:s');//最后修改时间
			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
		        //模块类
		        $moudObj = new moduleModel();
		        //模块列表
		        $mData = $moudObj->selectAll();
		        //模块角色类
		        $mRightObj = new moduleRightModel();
		        //角色模块类
		        $roleModuleObj = new roleModuleModel();
		
		        //修改角色
		        $model->updateByPkId($modelInfo);
		
		        //修改权限,先删除，后添加
		        $roleModuleObj->delPower($role_id);
		        foreach ($mData as $key => $value)
		        {
		            $moudleId = empty($_POST[$value['module_id']]) ? '' : $_POST[$value['module_id']];

		            if (!empty($moudleId))
		            {
		                $rightValue = array_sum($moudleId);
		
		                $roleModuleObj->insert(array("role_id" =>$role_id, "module_id" => $value['module_id'], "right_value" => $rightValue));
		            }
		        }

		        header("location:".$this->_manageDomain."roleManage/show/");
		        exit();
			}
		}
		else{
			$modelInfo = $model->selectById($role_id);
			if(!$modelInfo) {
				$this->sysMsg("记录不存在",1);
			}

	        $mRightObj = new moduleRightModel();
	        $mData = $mRightObj->selectAllModuleRightInfo();
	
	        //模块组
	        $moduleGroups = array();
	        //取所有的模块组
	        $lastGroup = '';
	        foreach ($mData as $key => $value)
	        {
	            if ($lastGroup != $value['module_group_id'])
	            {
	                $moduleGroups[] = array('module_group_id' => $value['module_group_id'], 'group_name' => $value['group_name'], 'group_sort' => $value['group_sort'], 'modules' => null);
	                $lastGroup = $value['module_group_id'];
	            }
	        }
	        //取Group的Module
	        foreach ($moduleGroups as & $groupValue)
	        {
	            $groupId = intval($value['module_group_id']);
	            $lastModuleID = 0;
	            foreach ($mData as & $value)
	            {
	                //echo $lastModuleID,'-',$value['module_id'],'<br />';
	                if ($value['module_group_id'] == $groupValue['module_group_id'] && intval($value['module_id']) != $lastModuleID)
	                {
	                    $arrayRights = array();
	                    $lastModuleID = intval($value['module_id']);
	                    
	                     //todo:优化 用户权限
	                    $uRightValue=$mRightObj->selectByRoleModule($role_id,$value['module_id']);                    
	                    
	                    //取Module的rights
	                    foreach ($mData as $moduleValue)
	                    {                        
	                        if ($value['module_id'] == $moduleValue['module_id'])
	                        {   
	                            $isCheck=false;
	                            if((intval($uRightValue) & intval($moduleValue['right_value'])) > 0)
	                               $isCheck=true;                           
	                              
	                            $arrayRights[] = array('module_right_id' => $moduleValue['module_right_id'], 'right_value' => intval($moduleValue['right_value']), 'right_name' => $moduleValue['right_name'], 'right_ename' => $moduleValue['right_ename'],'isCheck'=>$isCheck);
	                        }
	                    }
	                   
	                    
	                    $groupValue["modules"][] = array('module_id' => $value['module_id'], 'module_name' => $value['module_name'], 'module_sort' => $value['sort_num'],'rights' => $arrayRights);
	                }
	            }
	        }
		}
		
		$this->setViewParam('id', $role_id);
	    $this->setViewParam('roleName', $modelInfo['role_name']);
	    $this->setViewParam('description', $modelInfo['description']);
		$this->setViewParam('rightData', $moduleGroups);
		
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"角色列表","href"=>$this->_manageDomain."roleManage/show/"),array("text"=>"角色修改")));
		$this->render("role/edit",array("error"=>$errorStr));
	}

	public function del()
	{
		$role_id = $this->getRequestData("id","GET");

		if($role_id)
		{
			$model = new roleModel();
			$model->delete($role_id);
		}
		
		$this->show();
	}
	
}
?>
